package com.xaicode.learn.netty.tcpStickyAndUnpacking;

import com.google.common.base.Strings;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 9:58
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private AtomicInteger count = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String message = new String(buffer, StandardCharsets.UTF_8);

        if (count.get() == 0) {
            log.info(Strings.repeat("-", 20) + "\r\n");
        }

        log.info("receive count [{}] msg: {}", count.incrementAndGet(), message);

        // reply
        ByteBuf reply = Unpooled.copiedBuffer(count.get() + " ", CharsetUtil.UTF_8);
        log.info("reply client [{}] msg: {}", ctx.channel().remoteAddress(), reply.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(reply);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
